import React from 'react';
import './css/login.less';
import { Link } from 'react-router-dom';
import {VALIDPHONE} from '../../utils/valid'
import {createCode} from '../../utils/common'
import http from '../../utils/http';
import Cookies from 'js-cookie'
import { Form } from 'react-validify'
// 校验
const rules = {
  account: ['required', `regex:${VALIDPHONE.reg}`],
  password: ['required'],
}
const errorMessages = {
  'required.account': '请输入注册使用的手机号',
  'regex.account': VALIDPHONE.errMsg,
  'required.password': '请输入密码',
}
let phoneCache = {}
let phoneMsg = ''
const placeholders = {
  account: '请输入手机号',
  password: '请输入密码',
  msgCode: '验证码'
}
class Login extends React.Component {
	state = {
		type: 1,
		account: '',
    password: '',
    textType: 'text',
    msgCode: '',
    setCode:'',
    showCode: false,
    isCanclick:true,
    submitError: '',
    placeholders: {
      account: placeholders.account,
      password: placeholders.password,
      msgCode: placeholders.msgCode
    },
    islodings:false
  }
  checkValid = (props) => {
    if (props.name==='account') {
      this.setState({})
    } 
  }
  // 校验组件
  Input = ({ error, onEnter, ...props }) => {
    // 异步
    if (props.name==='account' && props.value.length===11) {
      this.validphone(props)
    }
    return (
    <div>
      {/* <input {...props} style={{border: error ? '1px solid #C13431': '1px solid #586AE6'}} */}
      <input  autoComplete="off" {...props} style={{border: error || (props.name==='password' && this.state.submitError) ||  (props.name==='account' && props.value.length===11 && !error && phoneMsg)? '1px solid #C13431':''}}
       onBlur={(e)=>{
        props.onBlur(e);
        this.checkValid(props);
        const holders = this.state.placeholders
        holders[props.name] = placeholders[props.name]
        this.setState({
          placeholders: holders
        })
      }}/>
      {error ? <div className="error-msg">{error}</div> : ''}
      {props.name==='account' && props.value.length===11 && !error && phoneMsg?<div className="error-msg">{phoneMsg}</div>:''}
    </div>
  )};
  // 验证码校验
  validCode = value => {
    if(!value) {
      this.setState({
        setCode:''
      })
    }
    if(value && value.toLowerCase() !== this.state.msgCode.toLowerCase()) {
      this.setState({
        setCode:'验证码输入错误'
      })
    }
  }
	login = values => {
    const msgCode = this.state.msgCode || ''
    if (this.state.phoneMsg) return
    if (this.state.setCode) return
    if (this.state.showCode && (!msgCode.trim() || this.state.setCode)) return
    this.setState({
      isCanclick:false,
      islodings:true
    })
    // 校验
    const data = {
      // type: this.state.type,
      account: values.account,
      password: values.password
    }
    http.post('/login/parent', data)
    .then(data=> {

      this.setState({
        isCanclick:true,
        islodings:false
      })
      
      if(data){
        Cookies.set('token',data,{ expires: 6, path: '/' });
        const query = this.props.location.query
        // 直接返回页面不刷新
        if (query) {
          this.props.history.push(query)
        } else {
          this.props.history.push('/admin/')
        }
      }
    }, err => {
      this.setState({
        isCanclick:true,
        islodings:false
      })
      if (err) {
        if(err.code === 48004) {
          this.setState({
            submitError: err.msg
          })
        } 
        if(err.code === 48005) {
          this.getCode()
          this.setState({
            showCode: true,
            submitError: err.msg
          })
        }
      }
    })
  }
  validphone = (props) => {
    if (props.name==='account' && props.value.length === 11){
      if (!phoneCache[props.value]) {
        http.get('/register/isRegister',{
          params: {account: props.value}
        })
        .then(data=> {
          if (data) {
            phoneMsg = ''
            phoneCache[props.value] = 1
          } else {
            phoneMsg = '该手机号未注册'
            // this.setState({
            //   phoneMsg: '用户未注册'
            // })
            phoneCache[props.value] = 2
          } 
        }, err => {
          phoneCache[props.value] = 2
          if(err && err.code === 41003){
            phoneMsg = '该手机号未注册'
            // this.setState({
            //   phoneMsg: '用户未注册'
            // })
          }
        })
      } else if(phoneCache[props.value]===1) {
        phoneMsg = ''
        // this.setState({
        //   phoneMsg: ''
        // })
      } else if(phoneCache[props.value]===2) {
        phoneMsg = '该手机号未注册'
        // this.setState({
        //   phoneMsg: '用户未注册'
        // })
      }
    } 
  }
  clearHolder = (name) => {
    const holder = this.state.placeholders
    holder[name] = ''
    this.setState({placeholders: holder})
  }
  getCode = event => {
    event && event.preventDefault()
    const msgCode = createCode()
    this.setState({
      msgCode: msgCode
    })
	}
	componentDidMount () {
    // 每次跳转到页面清空缓存
    phoneCache = {}
    phoneMsg = ''
    this.setState({account: '', password: ''});
  }
  clearError = () => {
    this.setState({
      submitError: '',
    })
  }
 
	render() {
		return (
      <div className="row login">
        <Form  
          rules={rules}
          errorMessages={errorMessages}
          className="login-field login-all login-margin">
          <div className="login-register"><Link to="/register/">注册</Link></div>
          <div className="login-title text-center">账号登录</div>
          <div className="form-group filed-item">
            <div className="form-text">手机号</div>
            <this.Input 
                type="text"
                name="account"
                placeholder={this.state.placeholders.account}
                onFocus={()=>this.clearHolder('account')}
                className="input-form"/>
          </div>
          <div className="form-group filed-item">
            <div className="form-text">密码</div>
            <this.Input type={this.state.textType}
              name="password" placeholder={this.state.placeholders.password}
              onEnter={(values)=>{
                this.login(values);
              }}
              onFocus={()=>{
              this.setState({
                textType:'password'
              })
              this.clearHolder('password')
              this.clearError()
            }}
            className="input-form"/>
            <div className="error-msg">{this.state.submitError}</div>
          </div>
          {this.state.showCode?
          <div className="form-group row code">
            <div className="col-md-5 col-xs-5">
              <input
                autoComplete="off"
                placeholder={this.state.placeholders.msgCode}
                onBlur={(e)=>{
                  this.validCode(e.target.value)
                  const holders = this.state.placeholders
                  holders.msgCode = placeholders['msgCode']
                  this.setState({
                    placeholders: holders
                  })
                }}
                onFocus={()=>{
                  this.setState({
                    setCode:''
                  })
                  this.clearHolder('msgCode')
                }}
                style={{border: this.state.setCode ? '1px solid #C13431':''}}
                className="input-form"/>
              <div className="error-msg">{this.state.setCode}</div>
            </div>
            <div className="col-md-3 col-md-offset-1 col-xs-3 col-xs-offset-1 code-btn ">{this.state.msgCode}</div>
            <div className="col-md-3 col-xs-3 fresh"><a className="col-md-12 col-xs-12" href="javascript;" onClick={this.getCode}>刷新</a></div>
          </div>
          :''}
          <div className="forget">
            <Link to="/account/">忘记密码?</Link>
          </div>
          <div submit onClick={(values)=>{
              this.login(values);
            }}>
            {this.state.islodings?<img className="lodings" src={require('../../images/teacher-img/loding.svg')} alt="Loading icon" />:""}
            <input type="button" className="login-btn" value={this.state.islodings?"":"登录"} disabled={this.state.isCanclick?'':'disabled'}/>
          </div>
        </Form>
      </div>
		);
	}
}
export default Login;
